package com.second.app.thread.reentrant.interrupt;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gyz
 * @date 2021/2/2 16:06
 * lockInterruptibly()方法能够中断等待获取的线程，A,B两个线程通过lock.interruptibly()去获取锁，假设A线程获取到了锁。
 * 线程的B只有等待，此时如果threadB.interrupt()就能中断B线程的等待。
 * 如果使用lock.lock()方法，去获取锁，线程threadB.interrupt()方法，就不能中断B线程的等待。
 */
public class LockInterruptTest {
    public ReentrantLock lock = new ReentrantLock();

    public void waitMethod() {

        try {
            lock.lockInterruptibly();
            System.out.println("lock begin" + Thread.currentThread().getName());
            for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
                String string = new String();
                Math.random();
            }
            System.out.println("lock end " + Thread.currentThread().getName());
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
